<template>
  <div style="border: 1px solid #ccc;">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editor"
      :default-config="toolbarConfig"
      :mode="mode"
    />
    <Editor
      v-model="html"
      style="height: 500px; overflow-y: hidden;"
      :default-config="editorConfig"
      :mode="mode"
      @onCreated="onCreated"
      @onChange="onChange"
    />
  </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

export default {
  components: { Editor, Toolbar },
  props: {
    value: {
      type: String,
      default: '<p><br></p>'
    }
  },
  data() {
    return {
      editor: null,
      html: '<p></p>',
      toolbarConfig: { },
      editorConfig: { placeholder: '请输入内容...' },
      mode: 'default' // or 'simple'
    }
  },
  watch: {
    value(newValue) {
      // 当 prop 变化时更新本地数据，并且确保是有效的 HTML
      this.html = newValue || '<p><br></p>'
    }
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      this.html = this.value || '<p><br></p>' // 创建后赋值
    },
    onChange() {
      this.$emit('sendWangEditor', this.html)
    }
  }
}
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
